<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class QuestionController extends Controller
{
    public function index()
    {
        $questions = [];
        for ($i = 1;$i <= 440;$i ++) {
            $questions[$i] = [];
            $filename = $this->getFilename($i);
            if (\Storage::exists($filename)) {
                $questions[$i] = \json_decode(\Storage::get($filename), true);
            }
        }
        return view('question.index', \compact('questions'));
    }

    public function create()
    {
        return view('question.create');
    }

    public function store(Request $request)
    {
        $content = $request->post('content');

        try {
            $data = $this->contentParsing($content);
        } catch (\Exception $e) {
            \Session::flash('message', $e->getMessage());
            \Session::flash('content', $content);
            return back(); 
        }

        return view('question.confirm', \compact('data'));
    }

    public function confirm(Request $request)
    {
        $data = $request->post();
        
        $filename = $this->getFilename($data['number']);
        \Storage::put($filename, \json_encode($data, \JSON_UNESCAPED_UNICODE));
        \Session::flash('message', '保存成功');
        return \redirect(route('questions.create'));
    }

    public function view(int $id)
    {
        $filename = $this->getFilename($id);
        $question = [];
        if (\Storage::exists($filename)) {
            $question = \json_decode(\Storage::get($filename), true);
        }

        $prevId = $id - 1;
        // while ($prevId > 0 && !\Storage::exists($this->getFilename($prevId))) {
        //     $prevId --;
        // };
        $nextId = $id + 1;
        // while ($nextId > 0 && !\Storage::exists($this->getFilename($nextId))) {
        //     $nextId ++;
        // };

        $prev = route('questions.view', ['id' => $prevId]);
        $next = route('questions.view', ['id' => $nextId]);
        return view('question.view', \compact('question', 'prev', 'next'));
    }

    private function getFilename($number): string
    {
        return sprintf('questions/QUESTION-%s.json', $number);
    }

    private function contentParsing(string $content)
    {
        $data = [];
        if (!preg_match('/QUESTION (\d+)/i', $content, $match)) {
            throw new \Exception('没有匹配到题号');
        }
        $data['number'] = trim($match[1]);
        if (!preg_match('/QUESTION \d+\s+((?:(?!A\.).)+)/is', $content, $match)) {
            throw new \Exception('没有匹配到题目');
        }
        $data['title'] = trim($match[1]);
        if (!preg_match_all('/(?:\n)([A-Z]\.\s*((?:(?!Correct Answer\:).)+)*)/is', $content, $matchs)) {
            throw new \Exception('没有匹配到选项');
        }
        $data['options'] = trim($matchs[1][0]);
        if (!preg_match('/Correct Answer: ([A-Z]+)/i', $content, $match)) {
            throw new \Exception('没有匹配到答案');
        }
        $data['answer'] = trim($match[1]);
        return $data;
    }

    // private function contentParsingOptions(string $content)
    // {
    //     $options = [];
    //     for ($i = 0;$i < strlen($content);$i ++) {
    //         if ($content[$i] >= 65 && $content[$i] <= 90) {

    //         }
    //     }
    //     return $options;
    // }
}
